package cn.edu.swu.wwy.io;


import java.io.*;
import java.net.URL;

public class FileUtils {
    //从URL下载图片并保存到指定路径
    public static void saveImage(String url, String savePath) throws IOException{
        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
        FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024 * 4];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }catch (IOException e) {
            throw new RuntimeException("图片下载失败:" + e);
        }
    }

    //检查目录是否存在，不存在则创建
    public static void ensureDirectoryExists(String dirPath) {
        File file = new File(dirPath);
        if (file.isFile()) {
            //如果是文件，取文件目录创建
            file.getParentFile().mkdirs();
        }else {
            file.mkdirs();
        }
    }

    // 将下载记录追加到download_log.txt
    public static void appendLog(String log) {
        try(FileWriter fileWriter = new FileWriter("download_log.txt",true)) {
            fileWriter.write(log + "\n");
        }catch (IOException e){
            System.err.println("日志记录失败：" + e);
        }
    }
}
